/**
 * 
 */
package com.humanmonth.framework.web.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.humanmonth.framework.dao.JDOTemplate;

/**
 * @author 林子龙
 * 
 */
@SuppressWarnings("serial")
public abstract class AutoMapperServlet extends HttpServlet {
	private static final String CONTENT_TYPE = "text/html; charset=UTF-8";

	private Logger log = Logger.getLogger(this.getClass().getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType(CONTENT_TYPE);
		request.setCharacterEncoding("UTF-8");
		try {
			doAction(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			JDOTemplate.closePm();
		}
	}

	/**
	 * 
	 */
	public void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException, Exception {
		String action = ServletUtil.getStringParameterWithTrim(request, "action");
		log.info("接收到请求："+action);
		for (Method method : this.getClass().getMethods()) {
			if (method.isAnnotationPresent(Action.class) && method.getAnnotation(Action.class).value().equals(action)) {
				method.invoke(this, request, response);
				return;
			}
		}
		throw new RuntimeException("接收到不能处理的请求，aciton为：" + action);
	}

}
